import axios, { AxiosRequestConfig } from 'axios'
import { ApiRes } from '@/types/data'
import { useStorage } from '@/hooks/useStorage'
import { USER_KEY } from '@/store/modules/user'

import store from '@/store'
import { setInfo } from '@/store/modules/user'
import { User } from '@/types/user'
import router from '@/router'

const storage = useStorage()
const instance = axios.create({
  baseURL: import.meta.env.VITE_BASEURL
})

// 请求拦截器
instance.interceptors.request.use(
  function (config) {
    const token = storage.getStorage(USER_KEY)?.token
    // 在发送请求之前做些什么
    // 获取token，如果有token则携带
    if (token) {
      config.headers.token = token
    }

    return config
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

// 添加响应拦截器
instance.interceptors.response.use(
  function (response) {
    if (response.data.code === 206) {
      // 代表token非法。并且token清除做跳转登录
      store.dispatch(setInfo({} as User))

      // 跳转登录
      console.log(router)
      if (router.state.location.pathname !== '/login') {
        router.navigate(`/login?redirect=${router.state.location.pathname}`)
      }
    }
    return response.data
  },
  function (error) {
    return Promise.reject(error)
  }
)

export const request = <T>({
  url,
  method = 'GET',
  data
}: AxiosRequestConfig) => {
  return instance<any, ApiRes<T>>({
    url,
    method,
    [method?.toLowerCase() === 'get' ? 'params' : 'data']: data
  })
}
